package com.qf.hospital.realm;

import com.alibaba.druid.util.StringUtils;
import com.qf.hospital.entity.SysUser;
import com.qf.hospital.enums.HospitalExceptionEnum;
import com.qf.hospital.exception.HosptialException;
import com.qf.hospital.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author 何星宇
 * @version V1.0
 * @Date 2021/10/15 11:25
 */
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;

    public static final Integer HASH_ITERATIONS = 1024;
    private Logger log = LoggerFactory.getLogger(CustomRealm.class);

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //解密
        {
            HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
            matcher.setHashAlgorithmName("MD5");
            matcher.setHashIterations(HASH_ITERATIONS);
            this.setCredentialsMatcher(matcher);
        }

        //获取token中存储的用户名
        String loginName = (String) token.getPrincipal();
        //校验
        if (StringUtils.isEmpty(loginName)){
            log.info("【登录】 用户名不能为null");
            throw new HosptialException(HospitalExceptionEnum.USERNAME_PASSWORD_ERROR);
        }

        //根据用户名去数据库查询用户信息
        SysUser sysUser = sysUserService.findSysUserByLoginName(loginName);
        //校验
        if (sysUser==null){
            log.info("【登录】 用户名不存在");
            throw new AuthenticationException();
        }

        //将用户信息和密码设置到返回结果中
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser,sysUser.getPwd(),"CustomRealm");

        //设置盐
        info.setCredentialsSalt(ByteSource.Util.bytes(sysUser.getSalt()));
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }


}
